<?php
/**
 * Created by PhpStorm.
 * User: renyi
 * Date: 2017/7/23
 * Time: 下午19:40
 */

namespace App\Helper;

class DataHelper
{
    /**
     * 计算总和 按照设定进行排序
     *
     * @param $data_source
     * @param $fields
     * @param $field_sort
     * @param $data_all
     * @param $total_all
     */
    public static function rearrange($data_source, $fields, $field_sort, &$data_all, &$total_all)
    {
        $sort = [];

        foreach ($data_source as $data)
        {
            $simple_data = [];

            // 排序用的值
            $sort[] = $data[$field_sort];

            // 简化数值 + 计算总量
            foreach ($fields as $field)
            {
                $field_id = $field['id'];
                $flag_sum = $field['flag_sum'];

                // 简化数值
                $simple_data[$field_id] = $data[$field_id];

                // 计算总量
                if ($flag_sum)
                {
                    $total_all[$field_id] += $data[$field_id];
                }
            }

            $data_all[] = $simple_data;
        }

        // 排序
        array_multisort($sort, SORT_DESC, $data_all);
    }

    public static function sort($data_source, $field_sort)
    {
        $sort = [];

        foreach ($data_source as $data)
        {
            // 排序用的值
            $sort[] = $data[$field_sort];
        }

        // 排序
        array_multisort($sort, SORT_DESC, $data_source);

        return $data_source;
    }

    public static function cut($source, $length = 10)
    {
        return array_slice($source, 0, $length);
    }

    /**
     * 显示百分数
     *
     * @param $numerator
     * @param $denominator
     * @return string
     */
    public static function percentage($numerator, $denominator)
    {
        if ($denominator == 0)
        {
            return "-";
        }

        return sprintf("%.2f%%", $numerator * 100 / $denominator);
    }

    /**
     * 将数组加重
     *
     * @param $elements
     * @return array
     */
    public static function important_all($elements)
    {
        $ret = [];

        foreach ($elements as $element)
        {
            $ret[] = self::important($element);
        }

        return $ret;
    }

    /**
     * 加重某元素
     * @param $element
     * @return string
     */
    public static function important($element)
    {
        return "<h4><b>".$element."</b></h4>";
    }

    /**
     * 输出xml字符
     * @param $params 参数名称
     * @return string 返回组装的xml
     **/
    public static function array_to_xml( $params )
    {
        if(!is_array($params)|| count($params) <= 0)
        {
            return false;
        }
        $xml = "<xml>";
        foreach ($params as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }
}
